<template>
    <div class="app-container">
        <div class="search-container">
            <el-form v-show="showSearch" ref="queryParamsRef" :inline="true" :model="queryParams" label-width="80px">
                <el-form-item label="类别代码" prop="classCode">
                    <el-input v-model="queryParams.classCode" clearable placeholder="请输入类别代码"
                        @keyup.enter.native="handleQuery" />
                </el-form-item>
                <el-form-item label="类别名称" prop="className">
                    <el-input v-model="queryParams.className" clearable placeholder="请输入类别名称"
                        @keyup.enter.native="handleQuery" />
                </el-form-item>
                <div style="float: right" class="mr20">
                    <query-form-button @handleQuery="handleQuery" @resetQuery="resetQuery" />
                </div>
            </el-form>
        </div>
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button v-hasPerm="['base:drugClassDict:add']" plain type="primary" @click="handleAdd"><template
                        #icon>
                        <i-ep-plus />
                    </template>新增
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button plain type="info" @click="toggleExpandAll"><template #icon>
                        <i-ep-sort />
                    </template>展开/折叠
                </el-button>
            </el-col>
        </el-row>

        <el-table v-if="refreshTable" v-adaptive="36" :data="drugClassDictList" :header-cell-style="$headerCellStyle"
            :default-expand-all="isExpandAll" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
            :border="true" row-key="id" :stripe="true">
            <el-table-column label="类别代码" prop="classCode" />
            <el-table-column :align="'center'" label="类别名称" prop="className" width="500px" />
            <el-table-column :align="'center'" label="排序" prop="sort" />
            <el-table-column :align="'center'" label="备注信息" prop="remarks" />
            <el-table-column :align="'center'" class-name="small-padding fixed-width" label="操作">
                <template #default="scope">
                    <el-button v-hasPerm="['base:drugClassDict:edit']" type="success"
                        @click="handleUpdate(scope.row)"><template #icon>
                            <i-ep-edit />
                        </template>修改
                    </el-button>
                    <el-button v-hasPerm="['base:drugClassDict:add']" type="primary"
                        @click="handleAdd(scope.row)"><template #icon>
                            <i-ep-plus />
                        </template>新增
                    </el-button>
                    <el-button v-hasPerm="['base:drugClassDict:remove']" type="danger"
                        @click="handleDelete(scope.row)"><template #icon>
                            <i-ep-delete />
                        </template>删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 添加或修改药品功效类别字典对话框 -->
        <el-dialog :close-on-click-modal="false" :title="title" v-model="open" append-to-body width="500px">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="父级" prop="parentId">
                    <drug-class :value="form.parentId" @org-node-click="drugTypeNodeClick" style="width: 100%;" />
                </el-form-item>
                <el-form-item label="类别代码" prop="classCode">
                    <el-input v-model="form.classCode" placeholder="请输入类别代码" />
                </el-form-item>
                <el-form-item label="类别名称" prop="className">
                    <el-input v-model="form.className" placeholder="请输入类别名称" />
                </el-form-item>
                <el-form-item label="排序" prop="sort">
                    <el-input v-model="form.sort" placeholder="请输入序号" type="number" />
                </el-form-item>
                <el-form-item label="备注信息" prop="remarks">
                    <el-input v-model="form.remarks" placeholder="请输入备注信息" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import {
  addDrugClassDict,
  delDrugClassDict,
  getDrugClassDict,
  listDrugClassDict,
  updateDrugClassDict
} from "@/api/drug/drugClassDict";

const { proxy } = getCurrentInstance() as any
const formRef = ref()
// 按钮loading
const buttonLoading = ref(false)
// 显示搜索条件
const showSearch = ref(true)
// 药品功效类别字典表格数据
const drugClassDictList = ref([])
// 药品功效类别字典表格数据(不是树结构)
const drugClassDictAll = ref([])
// 药品功效类别字典树选项
const drugClassDictOptions = ref([])
// 弹出层标题
const title = ref("")
// 是否显示弹出层
const open = ref(false)
// 是否展开，默认全部展开
const isExpandAll = ref(true)
// 重新渲染表格状态
const refreshTable = ref(true)
// 查询参数
const queryParamsRef = ref()
const queryParams = ref<any>({
    classCode: undefined,
    className: undefined,
    parentId: undefined,
    parentIds: undefined,
    remarks: undefined
})
// 表单参数
const form = ref<any>({})
// 表单校验
const rules = ref({
    id: [
        {
            required: true, message: "主键不能为空", trigger: "blur"
        }
    ],
    classCode: [
        {
            required: true, message: "类别代码不能为空", trigger: "blur"
        }
    ],
    className: [
        {
            required: true, message: "类别名称不能为空", trigger: "blur"
        }
    ],
    sort: [
        {
            required: true, message: "排序不能为空", trigger: "blur"
        }
    ],
})
getList()
/** 查询药品功效类别字典列表 */
function getList() {
    listDrugClassDict(queryParams.value).then((response: any) => {
        drugClassDictAll.value = response.data
        drugClassDictList.value = proxy.$handleTree(response.data, "id", "parentId");
    });
}
// 取消按钮
function cancel() {
    open.value = false;
    reset();
}
// 表单重置
function reset() {
    form.value = {
        id: null,
        classCode: null,
        className: null,
        parentId: null,
        parentIds: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remarks: null
    };
}

function drugTypeNodeClick(data) {
    form.value.parentId = data.id
}
/** 搜索按钮操作 */
function handleQuery() {
    getList();
}
/** 重置按钮操作 */
function resetQuery() {
    queryParamsRef.value.resetFields()
    handleQuery();
}
/** 新增按钮操作 */
function handleAdd(row) {
    reset();
    if (row != null && row.id) {
        form.value.parentId = row.id;
    } else {
        form.value.parentId = 0;
    }
    open.value = true;
    title.value = "添加药品功效类别字典";
}
/** 展开/折叠操作 */
function toggleExpandAll() {
    refreshTable.value = false;
    isExpandAll.value = !isExpandAll.value;
    nextTick(() => {
        refreshTable.value = true;
    });
}
/** 修改按钮操作 */
function handleUpdate(row) {
    reset();
    getDrugClassDict(row.id).then(response => {
        open.value = true;
        form.value = response.data;
        title.value = "修改药品功效类别字典";
    });
}
/** 提交按钮 */
function submitForm() {
    (formRef.value as any).validate(valid => {
        if (valid) {
            buttonLoading.value = true;
            // let index = drugClassDictAll.value.findIndex((item: any) => {
            //     return item.className === form.value.className
            // })
            // if ((index > -1 && form.value.id !== drugClassDictAll.value[index].id)
            //     || (index > -1 && !form.value.id)) {
            //     buttonLoading.value = false;
            //     return ElMessage.error("名称已存在，请重新修改名称")
            // }
            buttonLoading.value = true;
            if (form.value.id != null) {
                updateDrugClassDict(form.value).then(() => {
                    ElMessage.success("修改成功");
                    open.value = false;
                    getList();
                }).finally(() => {
                    buttonLoading.value = false;
                });
            } else {
                addDrugClassDict(form.value).then(() => {
                    ElMessage.success("新增成功");
                    open.value = false;
                    getList();
                }).finally(() => {
                    buttonLoading.value = false;
                });
            }
        }
    });
}
/** 删除按钮操作 */
function handleDelete(row) {
    let type = true
    let index = drugClassDictList.value.findIndex((item: any) => {
        return row.id === item.id
    })
    if (index > -1) {
        if (drugClassDictList.value[index].children.length > 0) {
            type = false
        }
    }
    ElMessageBox.confirm(`是否确认删除药品功效类别名称为"${row.className}"的数据项？`,
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        if (type) {
            delDrugClassDict(row.id).then(() => {
                if (type) {
                    getList();
                    ElMessage.success("删除成功");
                } else {
                    type = true
                    return ElMessage.error("此类别存在子项目，不能删除")
                }
            })
        }
    }).catch(() => {
    })
}
</script>

<script lang="ts">
export default {
    name: "DrugClassDict"
};
</script>

<style scoped></style>
